const enterpriseVue = new Vue({
  el: '#app',
  data() {
    const Parent_Number = (rule, value, callback) => {
      if (this.form.Level != '1' && !value) {
        callback(new Error('当前菜单等级不是一级菜单，请选择父级菜单'));
      } else {
        callback();
      }
    }
    const Url = (rule, value, callback) => {
      if (this.children == '否' && !value) {
        callback(new Error('当前菜单不含子集，请输入菜单路由'));
      } else {
        callback();
      }
    }
    const Icon = (rule, value, callback) => {
      if (this.form.Level == '1' && !value) {
        callback(new Error('当前菜单是一级菜单，请选的菜单图标'));
      } else {
        callback();
      }
    }
    return {
      rules: {
        Model_Name: [{required: true, message: '请选择菜单名称', trigger: 'blur'}],
        Level:[{ required: true, message: '请选择菜单等级', trigger: 'blur'}],
        Parent_Number:[{required:true, validator:Parent_Number , trigger:'change'}],
        Url:[{required:true,validator:Url,trigger: 'blur'}],
        Icon:[{required:true,validator:Icon,trigger: 'change'}]
      },
      form: {
        Model_Number: '',
        Model_Name: '',
        Parent_Number: '',
        Level: '',
        Url: '',
        Path: '',
        Icon: '',
        Order: '',
        Children:{
          system_model_mark:[]
        }
      },
      Level: [{
        label: '一级菜单',
        value: '1'
      }, {
        label: '二级菜单',
        value: '2'
      }, {
        label: '三级菜单',
        value: '3'
      }],
      Role:[{
        label:'全部',
        value:'0'
      },{
        label:'仅平台',
        value:'1'
      },{
        label:'仅用户',
        value:'2'
      }],
      Icon:[],
      Parent: [],
      children: '否',
      loading: false,
      isParent: true,
      isUrl:false
    }
  },
  mounted() {
    this.getIcon()
    const Model_Number = sessionStorage.getItem("Model_Number")
    this.getData(Model_Number);
  },
  methods: {
    getData(Model_Number){
      const _this = this;
      $.ajax({
        url: DomainName + '/getSubtableInquiryOriginal?token='+ $.cookie('token'),
        type: 'POST',
        data:{
          Primary_Key:Model_Number,
          JSONObject:JSON.stringify({system_model_list:{system_model_mark:{}}})
        },
        success: function (res) {
          _this.form = res.system_model_list[0]
          if(_this.form.Url == ''){
            _this.children = '是'
            _this.isUrl = true
          }
          if(_this.form.Level != '1'){
            _this.isParent=false
            _this.getMenu(_this.form.Level)
          }
        },
        error: function () {
          _this.$message.error("操作失败，请稍后再试")
        },
        complete: function (XMLHttpRequest) {
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        }
      })
    },
    getIcon(){
      const _this = this;
      $.ajax({
        url: absolutepath() + 'js/Icon.json',
        type: 'GET',
        success: function (data) {
          _this.Icon = data
        },
      })
    },
    getMenu(e) {
      if (e != '1') {
        const _this = this;
        Level =  e-1+''
        $.ajax({
          url: DomainName + '/getLevelMenuAction?Level='+Level,
          type: 'GET',
          success: function (res) {
            _this.Parent = res
            _this.isParent = false
          },
          error: function () {
            _this.$message.error("操作失败，请稍后再试")
          },
          complete: function (XMLHttpRequest) {
            if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
              window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
            }
          }
        })
      }else{
        this.Parent = []
        this.isParent = true
        this.form.Parent_Number = ''
        this.children = '是'
        this.getUrl(this.children)
      }
    },
    getUrl(e){
      if(e === '是'){
        this.isUrl = true
        this.form.Url = ''
      }else if(e === '否'){
        this.isUrl = false
      }
    },
    submitForm(formName) {
      let _this = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          _this.loading = true
          const { add, modify } = _this.deal()
          let data = {}
          if (add == null) {
            data = { Data: JSON.stringify({ Modify: { system_model_list: [modify] } })}
          } else {
            data = { Data: JSON.stringify({ Modify: { system_model_list: [modify] }, Add: { system_model_list: [add], }}),}
          }
          $.ajax({
            url: `${DomainName}/getEditAction?token=${$.cookie("token")}`,
            type: 'POST',
            data,
            success: function (res) {
              if (res.Status === 'success') {
                _this.$message.success("提交成功")
                window.history.go(-1)
              } else {
                _this.$message.error("提交失败，请稍后再试")
              }
            },
            error: function () {
              _this.$message.error("操作失败，请稍后再试")
            },
            complete: function (XMLHttpRequest) {
              _this.loading = false
              if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
              }
            }
          })
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    deal() {
      const add = deepClone(this.form)
      const modify = deepClone(this.form)
      let add_system_model_mark = [], modify_system_model_mark = []

      for (const i in modify.Children.system_model_mark) {
        const obj = modify.Children.system_model_mark[i];
        if (!Object.keys(obj).some(item => item.includes('_Original'))) {
          add_system_model_mark.push(obj)
        } else {
          modify_system_model_mark.push(obj)
        }
      }
      
      add.Children.system_model_mark = add_system_model_mark
      modify.Children.system_model_mark = modify_system_model_mark

      if (add_system_model_mark.length == 0) {
        return { add: null, modify };
      }
      return { add, modify };
    },
    add_system_model_mark(){
      this.form.Children.system_model_mark.push({
        Mark_Number: '',
        Model_Number: this.form.Model_Number,
        Mark_Name: ''
      })
      
    },
    remove_system_model_mark(){
      if (this.form.Children.system_model_mark.filter(item => item.Row_Status != '1').length > 0) {
        let i = this.form.Children.system_model_mark.filter(item => item.Row_Status != '1').length - 1
        let obj = this.form.Children.system_model_mark.filter(item => item.Row_Status != '1')[i]
        if (!Object.keys(obj).some(item => item.includes('_Original'))) {
          this.form.Children.system_model_mark.pop()
        } else {
          this.$confirm('警告！此操作将删除一条权限标识,可能会引起页面问题, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            this.form.Children.system_model_mark.filter(item => item.Row_Status != '1')[i].Row_Status = '1'
          }).catch(() => {
            this.$message({
              type: 'warning',
              message: '已取消删除'
            });
          });
        }
      }else{
        this.$message({
          message: '不能在删除了',
          type: 'warning'
        })
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  }
})